package com.bit.cfdi.web.inteceptor;

import java.util.Calendar;
import java.util.List;

import org.hibernate.event.SaveOrUpdateEvent;
import org.hibernate.event.def.DefaultSaveOrUpdateEventListener;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.bit.cfdi.web.domain.HistorialPassword;
import com.bit.cfdi.web.domain.Usuario;
import com.bit.cfdi.web.services.HistorialPasswordService;

public class CFDGenericSaveOrUpdateListener extends DefaultSaveOrUpdateEventListener 
	implements ApplicationContextAware {
	private static final long serialVersionUID = 3045420113251303668L;
	private ApplicationContext applicationContext;
	@Override
	public void onSaveOrUpdate(SaveOrUpdateEvent event) {
		//super.onSaveOrUpdate(event);
		if (event.getObject() instanceof Usuario) {
			Usuario usuario = (Usuario)event.getObject();
			HistorialPassword hPassword = new HistorialPassword();
			//if (applicationContext.getBean(UsuarioService.class).getAllFromUsuario() != null && 
					//applicationContext.getBean(UsuarioService.class).getAllFromUsuario().isEmpty()) {
				List<HistorialPassword> historialPassword = 
						 applicationContext.getBean(HistorialPasswordService.class).getFirstThreeRecords(usuario.getEmail());
				if (historialPassword != null && !historialPassword.isEmpty()) {
					 hPassword.setFecha(Calendar.getInstance());
					 hPassword.setPassword(usuario.getPassword());
					 hPassword.setUsuario(usuario);
					if (historialPassword.size() > 2 ) {
						 applicationContext.getBean(HistorialPasswordService.class).deleteMinIndex(historialPassword.get(0));
					}
					applicationContext.getBean(HistorialPasswordService.class).save(hPassword);
				} else {
					 hPassword.setFecha(Calendar.getInstance());
					 hPassword.setPassword(usuario.getPassword());
					 hPassword.setUsuario(usuario);
					 applicationContext.getBean(HistorialPasswordService.class).save(hPassword);
				}
			//}
		}
		super.onSaveOrUpdate(event);
	}
	

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}
	
}
